package test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.TermFreqVector;
import org.apache.lucene.search.Collector;
import org.apache.lucene.search.Scorer;

public class CircleCollector extends Collector {

	private IndexReader reader;
	private float cenx;
	private float ceny;
	private float radi;
	private List<String> terms = new ArrayList<String>();
	private List<Document> cirDocs = new ArrayList<Document>();
	private HashMap<String, Integer> hm = new HashMap<String, Integer>();

	public CircleCollector(IndexReader reader, float cenx, float ceny, float radi, List<String> terms) {
		super();
		// TODO Auto-generated constructor stub
		this.reader = reader;
		this.cenx = cenx;
		this.ceny = ceny;
		this.radi = radi;
		this.terms = terms;
	}

	@Override
	public boolean acceptsDocsOutOfOrder() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void collect(int arg0) throws IOException {
		// TODO Auto-generated method stub
		Document doc = reader.document(arg0);
		float docx = Float.parseFloat(doc.get("x"));
		float docy = Float.parseFloat(doc.get("y"));
		float dist = (float) Math.sqrt(Math.pow(cenx - docx, 2) + Math.pow(ceny - docy, 2));
		if(dist <= radi){
			cirDocs.add(doc);
			TermFreqVector tfv = reader.getTermFreqVector(arg0, "content");
			for(int i = 0; i < terms.size(); i++){
				int index = tfv.indexOf(terms.get(i));
				if(index != -1){
					if(hm.get(terms.get(i)) != null){
						int df1 = hm.get(terms.get(i));
						df1++;
						hm.put(terms.get(i), df1);
					}else{
						hm.put(terms.get(i), 1);
					}
				}
			}
		}		
	}

	public List<Document> getDocs(){
		return cirDocs;
	}
	
	public HashMap<String, Integer> getHashMap(){
		return hm;
	}

	@Override
	public void setNextReader(IndexReader arg0, int arg1) throws IOException {
		// TODO Auto-generated method stub
		this.reader = arg0;
	}

	@Override
	public void setScorer(Scorer arg0) throws IOException {
		// TODO Auto-generated method stub
	}
}
